//
//  ZYHistoricalRecordController.m
//  BestLearning
//
//  Created by ちょうかんこん on 2017/11/1.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "ZYHistoricalRecordController.h"
#import "ZYHistoricalRecordCell.h"
#define kCell @"cell"

#import "ZYHistoricalRecordModel.h"
#import "HNTeacgerEvaluateDetailController.h"
#import "LLNavigationMidSearchItem.h"
#import "ReplyView.h"
#import "ZYNewsMessageController.h"
#import "ZYConmentDetailsController.h"
#import "HMFiltrateView.h"
#import "HNThreeGoodEvaView.h"
#import "HNCourseListChartsModel.h"
#import "HMTeacgerEvaluateDetailVC.h"
@interface ZYHistoricalRecordController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,assign) BOOL isTrue;
@property (nonatomic,assign) NSInteger page;
@property(nonatomic,strong)UILabel *nameLbel;
@property(nonatomic,strong)UILabel *teacherLabel;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)UIButton *seeButton;
@property (nonatomic,strong) UIButton *customButton;
@property (nonatomic,strong) LLNavigationMidSearchItem *midItem;
@property (nonatomic,strong) UITextField *searchTextField;
@property (nonatomic,strong) UIView *allView;

@property (nonatomic,assign) BOOL isSearch;
@property (nonatomic,assign) BOOL isSearchStraEnd;
@property (nonatomic,copy) NSString *starTime;
@property (nonatomic,copy) NSString *endTime;
@property (nonatomic,copy) NSString *searchStrTitle;
@property (nonatomic,copy) NSString *searchStudentName;

@property (nonatomic,strong) UIWindow *window;
@property (nonatomic,strong)  UIView  *windowView;
@property (nonatomic,strong) HMFiltrateView *payView;


@end

@implementation ZYHistoricalRecordController


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(245, 245, 245)] forBarMetrics:(UIBarMetricsDefault)];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];;

}

- (NSMutableArray *)dataSource {
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //self.title = @"评价记录";
    
    [self setUpSuperView];
    
    self.midItem = [[LLNavigationMidSearchItem alloc]init];
    self.midItem.frame = CGRectMake(0, 0,kScreenWidth, 30);
    self.midItem.searchField.placeholder = @"   搜索课程、学生";
    self.midItem.layer.cornerRadius = 15;
    self.midItem.clipsToBounds = YES;
    self.navigationItem.titleView =self. midItem;
    self.searchTextField = self.midItem.searchField;
    self.searchTextField.delegate = self;
    self.searchTextField.returnKeyType =  UIReturnKeySearch;
    
    
    [self setUpRefresh];
    
    
    
    
    self.customButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.customButton.frame = CGRectMake(0, 0, 60, 20);
    [self.customButton setTitle:@"筛选" forState:(UIControlStateNormal)];
    [self.customButton setTitleColor:ColorRGB(102, 102, 102) forState:(UIControlStateNormal)];
    self.customButton.titleLabel.font = [UIFont systemFontOfSize:14];
    self.customButton.titleEdgeInsets = UIEdgeInsetsMake(0, -30,0,0);
    self.customButton.imageEdgeInsets = UIEdgeInsetsMake(0, 40,0, 0);
    
    [self.customButton setImage:[UIImage imageNamed:@"icon_seleted"] forState:(UIControlStateNormal)];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.customButton];
    [self.customButton addTarget:self action:@selector(allButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(Pop) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
    
}

- (void)Pop {
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)allButtonAction{
    
    

    self.navigationController.navigationBarHidden = YES;
    
    
//    UIWindow *window = [[UIWindow alloc] init];
//    window.frame = CGRectMake(0.f, 0.f, [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height);
//    window.windowLevel = UIWindowLevelNormal;
//     self.window.alpha = 1.f;
//     self.window.hidden = NO;
    
    
    
    HMFiltrateView *payView = [[[NSBundle mainBundle]loadNibNamed:@"HMFiltrateView" owner:nil options:nil] lastObject];
    payView.center =  self.view.center;
    


    
    [self.view addSubview:payView];
    
    
    payView.removeFromSuperviewBlock = ^(NSString *couseName, NSString *studentName, NSString *startTime, NSString *endTime) {
        
        
        NSLog(@"%@ %@ %@  %@",couseName,studentName,startTime,endTime);
        
        if ([startTime isEqualToString:@"开始时间"]) {
            
            startTime = @"";
            
        }
        
        if ([endTime isEqualToString:@"结束时间"]) {
             endTime = @"";
        }
        

        self.starTime = startTime;
        self.endTime = endTime;
        self.searchStrTitle = couseName.length > 0?couseName:@"";
        self.searchStudentName = studentName.length >0?studentName:@"";
        
        [self searchName];
       self.navigationController.navigationBarHidden = NO;
       
    };
    
    
    self.payView = payView;
 
    
    
    
    
}

- (void)searchName{
    
    [self.payView removeFromSuperviewPush];
    
    self.isSearchStraEnd = YES;
    self.isSearch = NO;
    
    [self.tableView.mj_header beginRefreshing];
}







#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}

- (void)setNetWork{
    
    
   // http://192.168.0.226:8080/StarShine/ys/historyComment.do?action=getCommentDataByParams&pageNumber=1&name=随心&petname=小&startTime=2017-06-15&endTime=2017-06-19&searchName=资源
    
    
    NSString *url;
    
    if (self.isSearch) {
        NSString *changeStr = [NSString stringWithFormat:@"historyComment.do?action=getCommentDataByParams&searchName=%@&name=&petname=&startTime=&endTime=&pageNumber=%ld",self.searchTextField.text,(long)self.page];
        
        url = [changeStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
    }else if (self.isSearchStraEnd){
        
        NSString *chanStr = [NSString stringWithFormat:@"historyComment.do?action=getCommentDataByParams&name=%@&petname=%@&startTime=%@&endTime=%@&searchName=&pageNumber=%ld",self.searchStrTitle,self.searchStudentName,self.starTime,self.endTime,(long)self.page];
        
        
        url = [chanStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        
        
        
        
    }else{
        
        
        url = [NSString stringWithFormat:@"historyComment.do?action=getCommentDataByParams&name=&petname=&startTime=&endTime=&searchName=&pageNumber=%ld",(long)self.page];
    }
    
    
    
    
    
    
    
    
    
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        [SVProgressHUD dismiss];
        
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            if (self.isTrue == YES) {
                [self.dataSource removeAllObjects];
            }
            NSDictionary *t = [Obj valueForKey:@"t"];
            
            NSArray *arr = [t valueForKey:@"dataList"];
            
        
            
            
            
            
            
            
            
            
            
            for (NSDictionary *dict in arr) {
                
                ZYHistoricalRecordModel *model = [ZYHistoricalRecordModel new];
                
                
                model.ID = [dict valueForKey:@"id"];
                
                
                [model setValuesForKeysWithDictionary:dict];
                
                
                [self.dataSource addObject:model];
                
                
                
                NSArray *arrTow = [dict valueForKey:@"elementCount"];
                
                if (![arrTow isKindOfClass:[NSNull class]]) {
                    
                    for (NSDictionary *dictTow in arrTow) {
                        
                        
                        HNCourseListChartsModel *modelTow = [[HNCourseListChartsModel alloc]init_ValuForKeyWithDict:dictTow];
                        [model.enementCount addObject:modelTow];
                        
                    }
                    model.heights = 44 + 30 * arrTow.count;
                }
                
                
                
              
                
                
                
                
            }
            
        }
        
        
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        
        
        
    } Fail:^(NSError *Error) {
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
    
    
}







- (void)setUpSuperView{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:(UITableViewStyleGrouped)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[ZYHistoricalRecordCell  class] forCellReuseIdentifier:kCell];
    self.tableView.estimatedRowHeight = 200;
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(-54, 0, 0, 0);
    self.tableView.tableFooterView = [UIView new];
    
    
    self.allView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
   
    self.tableView.tableHeaderView = self.allView;
    UIImageView *photoImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.allView.frame.origin.x,self.allView.frame.origin.y,self.allView.frame.size.width,self.allView.frame.size.height)];
    
    photoImageView.image = [UIImage imageNamed:@"bg_banner"];
    //photoImageView.contentMode = UIViewContentModeScaleAspectFill;
    photoImageView.clipsToBounds = YES;
    [self.allView addSubview:photoImageView];
    
    
    
    
    
    
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    ZYHistoricalRecordModel *model = self.dataSource[section];
    
    
    
    
    
    return model.lessonComments.count;
}






- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    ZYHistoricalRecordModel *model = self.dataSource[section];
    
    return 115 + model.heights;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    ZYHistoricalRecordModel *model = self.dataSource[section];
    
    
    
    
    UIView *vv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    vv.backgroundColor = [UIColor whiteColor];
    vv.tag = 2000 + section;
    
    self.nameLbel = [UILabel new];
    self.nameLbel.font = [UIFont systemFontOfSize:14];
    self.nameLbel.textColor = ColorRGB(51, 51, 51);
    [vv addSubview:self.nameLbel];
    
    
    self.teacherLabel = [UILabel new];
    self.teacherLabel.font = [UIFont systemFontOfSize:14];
    self.teacherLabel.textColor = ColorRGB(51, 51, 51);
    [vv addSubview:self.teacherLabel];
    
    self.timeLabel = [UILabel new];
    self.timeLabel.font = [UIFont systemFontOfSize:11];
    self.timeLabel.textColor = ColorRGB(102,102,102);
    [vv addSubview:self.timeLabel];
    
    
    
    UILabel *firstTimeLabel = [UILabel new];
    firstTimeLabel.font = [UIFont systemFontOfSize:11];
    firstTimeLabel.textColor = ColorRGB(102,102,102);
    [vv addSubview:firstTimeLabel];
    
    
    
    
    
    
    
    self.seeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.seeButton setTitle:@"查看评语  >" forState:(UIControlStateNormal)];
    [self.seeButton setTitleColor:ColorRGB(51, 51, 51) forState:(UIControlStateNormal)];
    self.seeButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [vv addSubview:self.seeButton];
    
    
    self.timeLabel.text = @"2015.10.11";
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(8);
        make.top.offset(10);
        
        
    }];
    
    
    
    
    self.nameLbel.text = @"评价课程名称";
    [self.nameLbel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.timeLabel);
        make.top.equalTo(self.timeLabel.mas_bottom).offset(8);
        
        
        
    }];
    
    
    self.teacherLabel.text = @"张宇老师";
    [self.teacherLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.nameLbel);
        make.top.equalTo(self.nameLbel.mas_bottom).offset(8);
        
    }];
    
    
    firstTimeLabel.text = @"家长首次查看时间：2012101021020102";
    [firstTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.teacherLabel);
        make.top.equalTo(self.teacherLabel.mas_bottom).offset(8);
    }];
    
   
    
    
    [self.seeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(vv).offset(-8);
        make.top.centerY.equalTo(self.teacherLabel);
    }];
    
    self.teacherLabel.text = [NSString stringWithFormat:@"学生：%@",[model.user valueForKey:@"petName"]];
    
    self.nameLbel.text = [NSString stringWithFormat:@"课程名称：%@",model.lessonName];
    self.timeLabel.text = [NSString stringWithFormat:@"%@",model.createTime];
    BOOL isUp = [NSString isBlankString:model.startTime];
    if (isUp) {
        firstTimeLabel.text = @"";
    }else {
         firstTimeLabel.text = [NSString stringWithFormat:@"家长首次查看时间：%@",model.startTime];
    }
   
    [self.seeButton addTarget:self action:@selector(seeButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    if (model.enementCount.count > 0) {
        
        HNThreeGoodEvaView *gv = [HNThreeGoodEvaView ConfigEvaViewWithDataArr:model.enementCount.copy CallBack:nil];
        [vv addSubview:gv];
        [gv mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(firstTimeLabel.mas_bottom).offset(0);
            make.left.equalTo(vv.mas_left).offset(0);
            make.right.equalTo(vv.mas_right).offset(0);
            make.height.equalTo(@(44 + 30 * model.enementCount.count));
        }];
        [gv layoutIfNeeded];
        
    }
    
    return vv;
    
}













- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYHistoricalRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:kCell forIndexPath:indexPath];
    
    
    
    ZYHistoricalRecordModel *model = self.dataSource[indexPath.section];
    
    
    
    
    
    
    
    
    if (model.lessonComments.count > indexPath.row) {
        
        ZYHistoricalSubRecordModel *modelTow = model.lessonComments[indexPath.row];
        
        
        [cell assignByZYHistoricalRecordModel:modelTow];
        
        
    }
    
    [cell.seeButton addTarget:self action:@selector(seeButtonTowAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    return cell;
}

#pragma mark --- 查看方法的实现
- (void)seeButtonAction:(UIButton *)sender{
    

    UIView *headerView =  sender.superview;
    ZYHistoricalRecordModel *model = self.dataSource[headerView.tag -2000];
    
    HMTeacgerEvaluateDetailVC *teacgVc = [HMTeacgerEvaluateDetailVC new];
//    HNTeacgerEvaluateDetailController *teacgVc = [HNTeacgerEvaluateDetailController new];
    teacgVc.ID = [NSString stringWithFormat:@"%@",model.ID];
    teacgVc.time = [NSString stringWithFormat:@"%@",model.isRead];
    teacgVc.SubjectTitle = model.lessonName;
    teacgVc.lessonId = [NSString stringWithFormat:@"%@",model.lessonId];
    teacgVc.enrollId = [NSString stringWithFormat:@"%@",model.enrollId];
    [self.navigationController pushViewController:teacgVc animated:YES];
    
    
    
    
    
}



#pragma mark --- 评论方法的实现
- (void)seeButtonTowAction:(UIButton *)sender{
        
    ZYHistoricalRecordCell *cell = (ZYHistoricalRecordCell *)sender.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ZYHistoricalRecordModel *model = self.dataSource[indexPath.section];
    ZYHistoricalSubRecordModel *modelTow = model.lessonComments[indexPath.row];
    
    
    
    ReplyView *View = [[ReplyView alloc] initReplyView];
    View.textFieldBlock = ^(NSString *text) {
        
        if ([text stringByReplacingOccurrencesOfString:@" " withString:@""].length <= 0) {
            [SVProgressHUD showSuccessWithStatus:@"请输入评论内容"];
        } else {
            
            [SVProgressHUD showWithStatus:@"上传中,请稍候"];
            
            
            
            
            NSDictionary *Params = @{
                                     @"action":@"saveCommentReply",
                                     @"commentId":[modelTow valueForKey:@"commentId"],
                                     @"content":text,
                                     @"replyId":[modelTow valueForKey:@"id"],
                                     @"replyUid":[[modelTow valueForKey:@"poster"] valueForKey:@"uid"]
                                     };
            
            
            
            [NetManager Post:LLBaseURLs(@"trainLesson.do") Auth:YES Params:Params Success:^(id Obj) {
                
                [SVProgressHUD dismiss];
                
                [self.tableView.mj_header beginRefreshing];
                
                
                
            } Fail:^(NSError *Error) {
                [SVProgressHUD dismiss];
            }];
            
            
        }
        
    };
    
    
    
    
    
    
    
    
    
    
    
    
}









//将要显示Cell的时候执行该代理方法
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //补齐分割线、两边延长
    [self replenishLine:cell];
}

//补齐分割线、两边延长
-(void)replenishLine:(UIView *)view{
    
    if ([view respondsToSelector:@selector(setSeparatorInset:)])
    {
        [(UITableViewCell *)view setSeparatorInset:UIEdgeInsetsZero];//注意这里：必须将view强制转换成（UITableViewCell ＊）类，不然会报错。
    }
    if ([view respondsToSelector:@selector(setLayoutMargins:)])
    {
        [view setLayoutMargins:UIEdgeInsetsZero];
    }
}





-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    [self.searchTextField resignFirstResponder];
}

//收回键盘
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [self.searchTextField resignFirstResponder];
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (self.searchTextField.text.length!=0) {
        
        
        self.isSearch = YES;
        self.isSearchStraEnd = NO;
        
        
        [self.tableView.mj_header beginRefreshing];
        
        
        
    }else{
        
        [self createAlertViewWithTitle:nil message:@"请输入搜索内容" preferredStyle:(UIAlertControllerStyleAlert) disapperaTime:1 andDis:nil];
    }
    
    return YES;
    
}















@end

